//
//  MySpeakerManager.h
//  wsgz
//  语音播报管理
//  Created by hzm on 16-8-16.
//  Copyright (c) 2016年 custom. All rights reserved.
//

#import "MySpeakerManager.h"
#import <AVFoundation/AVFoundation.h>
#import "AppUtils.h"


@interface MySpeakerManager()<AVSpeechSynthesizerDelegate>

@property (nonatomic, retain) NSMutableArray *needSpeakList;
@property (nonatomic, retain) AVSpeechSynthesizer *speaker;
@property (nonatomic, assign) BOOL isSpeaking;

@end


@implementation MySpeakerManager

+ (instancetype)sharedInstance
{
    static MySpeakerManager *instance;
    static dispatch_once_t pred;
    dispatch_once(&pred, ^{
        instance = [[MySpeakerManager alloc] init];
        [instance initNotification];
    });
    return instance;
}

- (void)initNotification
{
    [AppUtils addObserver:self selector:@selector(onAVAudioSessionInterruptionNotification:) name:AVAudioSessionInterruptionNotification];
}

- (void)dealloc
{
    [AppUtils removeObserver:self name:AVAudioSessionInterruptionNotification];
}

- (void)initSpeaker
{
    _speaker = [[AVSpeechSynthesizer alloc] init];
    _speaker.delegate = self;
    
    _needSpeakList = [[NSMutableArray alloc] init];
    
    _isSpeaking = NO;
}

- (void)onAVAudioSessionInterruptionNotification: (NSNotification *)notificaiton
{
    AVAudioSessionInterruptionType type = [notificaiton.userInfo[AVAudioSessionInterruptionTypeKey] intValue];
    if (type == AVAudioSessionInterruptionTypeBegan) {
        _isSpeaking = NO;
    }
}

- (void)speakString:(NSString *)str immediately:(BOOL)immediately
{
    if ([AppUtils isEmpty:str]) {
        return;
    }

    if (!immediately && _isSpeaking && [_needSpeakList count] < 1000) {
        [_needSpeakList addObject:str];
        return;
    }
    
//    [[AVAudioSession sharedInstance] setActive:YES error:nil];
//    [[AVAudioSession sharedInstance] setCategory:AVAudioSessionCategoryPlayback error:nil];
    
    AVSpeechUtterance *utterance = [AVSpeechUtterance speechUtteranceWithString:str];
    utterance.pitchMultiplier = 1.0f;
    utterance.volume = 1.0f;
    utterance.rate = IS_IOS9H ? 0.5f : 0.17f;
    AVSpeechSynthesisVoice *voice = [AVSpeechSynthesisVoice voiceWithLanguage:@"zh-CN"];
    utterance.voice = voice;
    [_speaker speakUtterance:utterance];
    
    _isSpeaking = YES;
}

- (void)speechSynthesizer:(AVSpeechSynthesizer *)synthesizer didFinishSpeechUtterance:(AVSpeechUtterance *)utterance
{
    _isSpeaking = NO;
    [self speakNext];
}

- (void)speechSynthesizer:(AVSpeechSynthesizer *)synthesizer didCancelSpeechUtterance:(AVSpeechUtterance *)utterance
{
    _isSpeaking = NO;
}

- (void)speakNext
{
    if ([_needSpeakList count] == 0) {
        return;
    }
    
    NSString *str = _needSpeakList[0];
    [_needSpeakList removeObjectAtIndex:0];
    [self speakString:str immediately:NO];
}

@end
